import yaml from 'js-yaml';
import fs from 'node:fs';
import path from 'node:path';
import binary from '@mapbox/node-pre-gyp';
import axios from 'axios';

export function electronSetup(){
  return {
    name: 'electron-setup',
    buildStart(options){
      const { VITE_APP_SHORT_NAME, VITE_SITE_URL, VITE_ELECTRON_APP_ID,VITE_GLOB_APP_TITLE } = process.env
      const rootPath = process.cwd()

      const pathResolve = (file) => {
        return path.resolve(rootPath, file)
      }

      const devAppUpdateYmlPath = pathResolve('dev-app-update.yml')

      let devAppUpdateYmlDoc = yaml.load(fs.readFileSync(devAppUpdateYmlPath, 'utf8'))
      devAppUpdateYmlDoc.url = `${VITE_SITE_URL}/work_ai/shotstack/electron-updater`
      devAppUpdateYmlDoc.updaterCacheDirName = `${VITE_APP_SHORT_NAME}-updater`

      fs.writeFileSync(devAppUpdateYmlPath, yaml.dump(devAppUpdateYmlDoc, {
        styles: {
          '!!str': 'plain'
        },
        lineWidth: -1
      }))

      const electronBuilderYmlPath = pathResolve('electron-builder.yml')
      let electronBuilderYmlDoc = yaml.load(fs.readFileSync(electronBuilderYmlPath, 'utf8'))

      electronBuilderYmlDoc.appId = VITE_ELECTRON_APP_ID
      electronBuilderYmlDoc.productName = VITE_APP_SHORT_NAME
      electronBuilderYmlDoc.directories.buildResources = `build/${VITE_APP_SHORT_NAME}`
      electronBuilderYmlDoc.win.executableName = VITE_APP_SHORT_NAME
      electronBuilderYmlDoc.nsis.shortcutName = VITE_GLOB_APP_TITLE
      electronBuilderYmlDoc.publish.url = `${VITE_SITE_URL}/work_ai/shotstack/electron-updater`

      fs.writeFileSync(electronBuilderYmlPath, yaml.dump(electronBuilderYmlDoc, {
        styles: {
          '!!str': 'plain'
        },
        lineWidth: -1
      }))

      // 清空并复制资源文件
      const resourcesPath = pathResolve('resources')
      const buildResourcesPath = pathResolve(`build/${VITE_APP_SHORT_NAME}`)

      // 确保目录存在
      if (!fs.existsSync(resourcesPath)) {
        fs.mkdirSync(resourcesPath, { recursive: true })
      }

      // 清空 resources 目录
      fs.readdirSync(resourcesPath).forEach(file => {
        const filePath = path.join(resourcesPath, file)
        fs.unlinkSync(filePath)
      })

      // 复制 build/zhimeitong 目录下的文件到 resources
      if (fs.existsSync(buildResourcesPath)) {
        fs.readdirSync(buildResourcesPath).forEach(file => {
          if (!file.startsWith('.env')) {
            const srcPath = path.join(buildResourcesPath, file)
            const destPath = path.join(resourcesPath, file)
            fs.copyFileSync(srcPath, destPath)
          }
        })
      }
    }
  }
}

export function electronSqliteDownload()
{
  return {
    name: 'electron-sqlite-download',

    async buildStart(options) {
      const sqlite3Path = path.resolve(path.join(process.cwd(), './node_modules/sqlite3/'));
      let bindingPath = binary.find(path.resolve(path.join(sqlite3Path, './package.json')));

      if (process.platform !== 'darwin') {
        return;
      }

      // 获取当前的平台架构
      const arch = process.arch;
      const sqliteArch = arch === 'arm64' ? 'x64' : 'arm64';

      // 从 bindingPath 中提取信息
      const regex = /napi-v(\d+)-(\w+)-(\w+)-(\w+)/;
      const match = bindingPath.match(regex);

      if (!match) {
        throw new Error('Unable to extract NAPI version and platform information from bindingPath');
      }

      const napiBuildVersion = match[1];
      const platform = match[2]; // 'darwin'
      const libc = match[3]; // 通常为 'unknown'

      bindingPath = bindingPath.replace(`-${arch}`, `-${sqliteArch}`);
      
      // 如果文件已存在，则返回
      if (fs.existsSync(bindingPath)) {
        return;
      }

      const dirPath = path.dirname(bindingPath);
      
      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
        console.log(`Created directory: ${dirPath}`);
      }

      // 获取 SQLite3 版本
      const version = JSON.parse(fs.readFileSync(path.join(sqlite3Path, 'package.json'))).version;

      // 构建下载 URL
      const url = `https://github.com/TryGhost/node-sqlite3/releases/download/v${version}/napi-v${napiBuildVersion}-${platform}-${libc}-${sqliteArch}.tar.gz`;

      // 下载文件
      const response = await axios({
        method: 'get',
        url,
        responseType: 'stream'
      });

      // 创建写入流
      const fileStream = fs.createWriteStream(bindingPath);

      // 管道将响应流写入文件
      response.data.pipe(fileStream);

      // 等待文件写入完成
      await new Promise((resolve, reject) => {
        fileStream.on('finish', resolve);
        fileStream.on('error', reject);
      });

      console.log(`Downloaded and saved to ${bindingPath}`);
    }
  }
}